﻿using System.Collections.Generic;
using System.Web.UI;
using System;

namespace ReportsFactory
{
    public static class Extensions
    {
        public static bool IsNull(this object obj)
        {
            return obj == null;
        }

        public static bool IsNotNull(this object obj)
        {
            return obj != null;
        }

        public static bool IsEmpty(this string str)
        {
            return string.IsNullOrWhiteSpace(str);
        }

        public static bool IsNotEmpty(this string str)
        {
            return !string.IsNullOrWhiteSpace(str);
        }

        private static List<Control> ctrls = new List<Control>();
        public static List<Control> GetAllControls(this Control ctrl)
        {
            foreach (Control item in ctrl.Controls)
            {
                ctrls.Add(item);
                if (item.Controls.Count > 0)
                    GetAllControls(item);
            }

            return ctrls;

        }

        public static Control GetPostBackControl(this Page sender)
        {
            Control control = null;
            string ctrlname = sender.Request.Params["__EVENTTARGET"];
            if (ctrlname != null && ctrlname != String.Empty)
            {
                control = sender.FindControl(ctrlname);
            }
            // if __EVENTTARGET is null, the control is a button type and we need to
            // iterate over the form collection to find it
            else
            {
                string ctrlStr = String.Empty;
                Control c = null;
                foreach (string ctl in sender.Request.Form)
                {
                    //handle ImageButton they having an additional "quasi-property" in their Id which identifies
                    //mouse x and y coordinates
                    if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                    {
                        ctrlStr = ctl.Substring(0, ctl.Length - 2);
                        c = sender.FindControl(ctrlStr);
                    }
                    else
                    {
                        c = sender.FindControl(ctl);
                    }
                    if (c is System.Web.UI.WebControls.Button ||
                             c is System.Web.UI.WebControls.ImageButton)
                    {
                        control = c;
                        break;
                    }
                }
            }
            return control;

        }
    }
}